package com.webmining.sherlock.service;

import com.webmining.sherlock.util.DataValidator;
import com.webmining.sherlock.util.FieldsValidator;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginService {

    public static void doLogin(HttpServletRequest request, HttpServletResponse response, ServletContext context) throws ServletException, IOException {
        if (hasEmptyRequiredFields(request)) {
            context.getRequestDispatcher("/").forward(request, response);
            return;
        }
        if (!DataValidator.isValidLoginData(request, response)) {
            context.getRequestDispatcher("/").forward(request, response);
            return;
        } else {
            response.sendRedirect("/");
        }

    }

    public static void doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().removeAttribute("loginWelcomeFieldAttribute");
        request.getSession().removeAttribute("isAdmin");
        response.sendRedirect("/");
    }

    private static boolean hasEmptyRequiredFields(HttpServletRequest request) {

        String email = request.getParameter("email");
        String password = request.getParameter("password");

        if (FieldsValidator.isEmptyField(email)) {
            request.setAttribute("loginFieldAttribute", FieldsValidator.EMPTY_FIELD_ERROR_MESSAGE);
            return true;
        }

        if (!FieldsValidator.isEmptyField(email) && FieldsValidator.isEmptyField(password)) {
            request.setAttribute("passwordFieldAttribute", FieldsValidator.EMPTY_FIELD_ERROR_MESSAGE);
            return true;
        }

        return false;
    }


}
